package com.xxxx.yeb.config.security;

import com.xxxx.yeb.pojo.Admin;
import com.xxxx.yeb.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Security配置类
 * @author
 * @since 1.0.0
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private IAdminService adminService;
	@Autowired
	private RestAuthorizationEntryPoint restAuthorizationEntryPoint;
	@Autowired
	private RestfulAccessDeniedHandler restfulAccessDeniedHandler;

//	@Autowired
//	private CustomFilter customFilter;
//	@Autowired
//	private CustomUrlDecisionManager customUrlDecisionManager;

	/**
	 * 这段配置是让security走登录逻辑的时候使用我们自己编写的UserDetailsService
	 * @param auth
	 * @throws Exception
	 */
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
	}

	/**
	 * 权限控制拦截地址过滤/不拦截设置
	 * @param web
	 * @throws Exception
	 */
	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers(
				"/login",
				"/logout",
				"/css/**",
				"/js/**",
				"/index.html",
				"favicon.ico",
				"/doc.html",
				"/webjars/**",
				"/swagger-resources/**",
				"/v2/api-docs/**",
				"/captcha",
				"/ws/**"
		);
	}

	/**
	 * security主要配置(核心)
	 * @param http
	 * @throws Exception
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		//使用JWT，不需要csrf
		http.csrf()
				.disable()
				//基于token，不需要session
				.sessionManagement()
				.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
				.and()
				// 授权请求
				.authorizeRequests()

//				//应许访问登录
//				.antMatchers("/login","logout")
//				.permitAll()
				//所有请求都要求认证
				.anyRequest()
				.authenticated()
				//动态权限配置
//				.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
//					@Override
//					public <O extends FilterSecurityInterceptor> O postProcess(O object) {
//						object.setAccessDecisionManager(customUrlDecisionManager);
//						object.setSecurityMetadataSource(customFilter);
//						return object;
//					}
//				})
				.and()
				//禁用缓存
				.headers()
				.cacheControl();
		//添加jwt 登录授权过滤器
		http.addFilterBefore(jwtAuthencationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
		//添加自定义未授权和未登录结果返回
		http.exceptionHandling()
				.accessDeniedHandler(restfulAccessDeniedHandler)
				.authenticationEntryPoint(restAuthorizationEntryPoint);
	}

	// ? 获取用户详情服务
	@Override
	@Bean
	public UserDetailsService userDetailsService() {
		return username -> {
			Admin admin = adminService.getAdminByUserName(username);
			if (null != admin) {
				return admin;
			}
			return null;
		};
	}


	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	@Bean
	public JwtAuthencationTokenFilter jwtAuthencationTokenFilter(){
		return new JwtAuthencationTokenFilter();
	}
}